package com.vectz.mgt.action;

import java.io.IOException;
import java.util.ArrayList;

import com.vectz.mgt.model.Entity;
import com.vectz.mgt.model.EntityOverview;
import com.vectz.mgt.util.Constant;
import com.vectz.mgt.util.Log;
import com.vectz.mgt.util.Util;
/**
 * @author ai-t.vn
 *
 */
public class DAOCodegenAction {
	ArrayList<Entity> listField=null;
	EntityOverview table = null;
	String outputFolder ="";
	public DAOCodegenAction(ArrayList<Entity> listField, EntityOverview table, String outputFolder)
	   			throws Exception {
		this.listField = listField;
		this.table = table;
		this.outputFolder = outputFolder;
		genernateDaoFile();
	}
	/*
	 * Generate DAO interface file
	 */
	public void genernateDaoFile()  throws Exception {
			String daoContent = "";
			String tmplIDaoContent = Util.readTextFileContent(Util
					.getTmplPath("dao","Dao-File.txt"));
			
			// add content path
			daoContent = genernateDaoFile(table, tmplIDaoContent);
			String fileLocation = new StringBuffer().append(outputFolder)
			.append(System.getProperty("file.separator"))
			.append("src")
			.append(System.getProperty("file.separator"))
			.append("dao")
			.append(System.getProperty("file.separator"))
			.append(table.getName())
			.append("Dao.java").toString();
			Util.writeJavaFile(fileLocation, daoContent);
			Log.log("Finish generate Dao file to: "+fileLocation);
	}
	/*
	 * Generate header file
	 */
	public String genernateDaoFile(EntityOverview table, String tmpContent) {
		if (Util.isEmpty(tmpContent))
			return "";
		//replace package name
		tmpContent = tmpContent.replaceAll("xxxxDaoPackageName", table
				.getPackageName());
		//replace DAO class name
		tmpContent = tmpContent
				.replaceAll("xxxxDaoClassName", table.getName()+"Dao");

		tmpContent = tmpContent.replaceAll("xxxxDAOName",Util.lowerCaseFirstChar(table.getName())+"Dao");
			
		tmpContent = tmpContent.replaceAll("xxxxName",
					new StringBuffer().append(table.getPackageName())
					.append(".model.")
					.append(table.getName())
					.toString());
		tmpContent = tmpContent.replaceAll("xxxxIdType", Util.getPKType(listField));
		
		tmpContent = tmpContent.replaceAll("xxxxIDaoClassName",new StringBuffer().
				append(table.getPackageName()+".dao.local.I"+table.getName()+"Dao").toString());
		return tmpContent;
	}

}
